<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /*
            思路：先根据首个元素进行排序。
            定义一个temp=intervals[0]，如果当前元素的第一个元素大于temp的尾元素，就合并
            如果没有，就先推入res数组中，然后更新temp
            */
            var merge = function (intervals) {
                intervals.sort((a, b) => a[0] - b[0])

                let temp = intervals[0]
                let result = []
                for (let i = 1; i < intervals.length; i++) {
                    if (intervals[i][0] <= temp[1]) {
                        temp[1] = Math.max(temp[1], intervals[i][1])
                    } else {
                        result.push(temp)
                        temp = intervals[i]
                    }
                }
                result.push(temp)
                return result
            }
            console.log(
                merge([
                    [1, 4],
                    [0, 4],
                ]),
            )
        </script>
    </body>
</html>
